/*
 * @Date: 2024-05-11 09:13:13
 * @LastEditTime: 2024-05-22 10:52:35
 * @Description:
 * @FilePath: \gas-report\src\utils\request.ts
 */
// http.js页面
//#ifdef H5

//#endif
const SUCCESS_CODE = [200, 201];
const ERROR_CODE = [401, "4401"];
const base_url = 'http://localhost:3000/'

export default (params) => {
  let token = "Bearer " + uni.getStorageSync("token");

	let url = base_url + params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let showLoading = params.loading;
	let header = {
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': token,
		...params.header
  }
  return new Promise((resolve, reject) => {
    if (showLoading) {
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });
    }
    if (method === "get" || method === "get") {
      let query = "";
      for (const key in data) {
        if (data[key] !== null && data[key] !== "") {
          if (query.length == 0) {
            query += `?${key}=${data[key]}`;
          } else {
            query += `&${key}=${data[key]}`;
          }
        }
      }
      url += query;
    }
    uni.request({
      url,
      method,
      data,
      header,
      timeout: 600000,
      success: (res) => {
        const { statusCode } = res;
        if (SUCCESS_CODE.includes(statusCode as number)) {
          if (ERROR_CODE.includes(res.data.code)) {
            uni.showToast({
              icon: "none",
              title: res.data.message || "网络出错,请稍后再试",
            });
            reject(res.data);
          } else {
            if (res.data.access_token) {
              resolve(res);
            }
            if (res.data.total) {
              resolve(res.data);
            } else {
              resolve(res.data);
            }
          }
        } else {
          if ([41201].includes(res.data.code)) {
            uni.removeStorageSync("token");
            uni.showToast({
              icon: "none",
              title: "登录过期,请重新登录",
            });
            uni.navigateTo({
              url: "/pages/login/index",
            });
          } else {
            uni.showToast({
              icon: "none",
              title: res.data.message || "网络出错,请稍后再试",
            });
          }
          reject(res.data);
        }
      },
      fail: (error) => {
        console.log("接口异常返参", error);
        const type = typeof error === "string";
        uni.showToast({
          icon: "none",
          title: type ? error : "网络出错,请稍后再试",
        });
        reject(error);
      },
      complete() {
        setTimeout(() => {
          showLoading && uni.hideLoading();
        }, 300);
      },
    });
  });
};

export const uploadFile = (url: string, file: Object, formData = {}) => {
  //   file.status = "uploading";
  //   file.message = "上传中...";
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${url}?filename=${file.file.name}`, //仅为示例，非真实的接口地址
      filePath: file.objectUrl,
      name: "file",
      formData,
      success(uploadFileRes) {
        // console.log("uploadFileRes", uploadFileRes);
        if (uploadFileRes.statusCode == 200) {
          const { data } = JSON.parse(uploadFileRes.data);
          file.status = "done";
          Object.assign(file, data);
          resolve(file);
        } else {
          file.status = "failed";
          file.message = "上传失败";
          resolve({});
        }
      },
      fail(err) {
        file.status = "failed";
        file.message = "上传失败";
        resolve({});
      },
    });
  });
};
